package com.shujia.hadoop.mr;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class MR02 {
    public static class WordMapper extends Mapper<LongWritable,Text,Text,LongWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString ( );
            String[] words = line.split (",");
            for (String word : words) {
             context.write (new Text (word),new LongWritable (1));
            }
        }
    }
    public static class WordReducer extends Reducer<Text,LongWritable,Text,LongWritable>{
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long count=0;
            for (LongWritable value : values) {
                count+=value.get ();
            }
            context.write (key,new LongWritable (count));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Job job = Job.getInstance ( );
        job.setJobName ("统计每行多个单词");
        job.setJarByClass (MR02.class);
        job.setMapperClass (WordMapper.class);
        job.setMapOutputKeyClass (Text.class);
        job.setMapOutputValueClass (LongWritable.class);
        job.setReducerClass (WordReducer.class);
        job.setOutputKeyClass (Text.class);
        job.setOutputValueClass (LongWritable.class);
        Path input = new Path ("/world.txt");
        FileInputFormat.addInputPath (job,input);
        Path output = new Path ("/output");
        FileSystem fs = FileSystem.get (new Configuration ( ));
        if (fs.exists (output)){
            fs.delete (output,true);
        }
        FileOutputFormat.setOutputPath (job,output);
        job.waitForCompletion (true);
        System.out.println ("统计一行多个单词" );



    }

}
